/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import VO.CPerro;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;

/**
 *
 * @author langeblanc
 */
public class CPerroDAO {

    public boolean insertar(CPerro perro) throws Exception {
        boolean flag = false;
        EntityManagerFactory emf = Persistence.
                createEntityManagerFactory("VeterinariaPU"); //conexión
        EntityManager em = emf.createEntityManager();//CRUD
        EntityTransaction trans = em.getTransaction();//iniciar-confirmar o descartar

        try {
            trans.begin();
            em.persist(perro);
            trans.commit();
            flag = true;
        } catch (Exception ex) {
            trans.rollback();
            throw new Exception("Error al guardar en la BD " + ex.getMessage());
        } finally {
            em.close();
        }

        return flag;
    }
    
    public boolean actualizar(CPerro perro) throws Exception {
        boolean flag = false;
        EntityManagerFactory emf = Persistence.
                createEntityManagerFactory("VeterinariaPU"); //conexión
        EntityManager em = emf.createEntityManager();//CRUD
        EntityTransaction trans = em.getTransaction();//iniciar-confirmar o descartar

        try {
            trans.begin();
            em.merge(perro);
            trans.commit();
            flag = true;
        } catch (Exception ex) {
            trans.rollback();
            throw new Exception("Error en la BD " + ex.getMessage());
        } finally {
            em.close();
        }

        return flag;
    }
    
    public boolean eliminar(CPerro perro) throws Exception {
        boolean flag = false;
        EntityManagerFactory emf = Persistence.
                createEntityManagerFactory("VeterinariaPU"); //conexión
        EntityManager em = emf.createEntityManager();//CRUD
        EntityTransaction trans = em.getTransaction();//iniciar-confirmar o descartar

        try {
            trans.begin();
            em.remove(em.merge(perro));
            trans.commit();
            flag = true;
        } catch (Exception ex) {
            trans.rollback();
            throw new Exception("Error en la BD " + ex.getMessage());
        } finally {
            em.close();
        }

        return flag;
    }
    
    public CPerro consultarPerroPorId(int codPerro){
        EntityManagerFactory emf = Persistence.
                createEntityManagerFactory("VeterinariaPU"); //conexión
        EntityManager em = emf.createEntityManager();//CRUD
        return em.find(CPerro.class, codPerro);
    }
}
